﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ChartSharp
{
    public class EncodingProcessor<TEncoder, TType> : IEncodingProcessor
        where TEncoder : BaseEncoder<TType>, new()
        where TType : struct, IComparable<TType>
    {
        protected TEncoder Encoder { get; private set; }

        public IEnumerable<IEnumerable<TType>> DataSets { get; private set; }

        public EncodingProcessor(IEnumerable<IEnumerable<TType>> dataSets)
        {
            Encoder = new TEncoder();
            DataSets = dataSets;
        }

        public EncodingProcessor(IEnumerable<TType> dataSet)
        {
            Encoder = new TEncoder();
            DataSets = new IEnumerable<TType>[] { dataSet };
        }

        #region IEncodingProcessor Members

        public string Generate()
        {
            string s = string.Empty;
            StringBuilder builder = new StringBuilder();

            builder.Append(Encoder.Prefix);
            builder.Append(":");

            DataSets.ToList().ForEach((dataSet) =>
            {
                dataSet.ToList().ForEach((number) =>
                {
                    builder.Append(Encoder.Convert(number));
                    builder.Append(Encoder.NumbersSeparator);
                });

                if (builder.Length > Encoder.NumbersSeparator.Length)
                {
                    builder.Length -= Encoder.NumbersSeparator.Length;
                }

                builder.Append(Encoder.DataSetsSeparator);
            });

            if (builder.Length > 0)
            {
                builder.Length--;
            }

            return builder.ToString();
        }

        #endregion
    }
}
